package com.woollen.controller;

import com.woollen.common.BaseResponse;
import com.woollen.common.ResultUtils;
import com.woollen.model.Member;
import com.woollen.model.dto.MemberRegisterRequest;
import com.woollen.model.dto.MemberLoginRequest;
import com.woollen.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;
import java.util.regex.Pattern;
import javax.servlet.http.HttpSession;
import java.util.Random;

@RestController
@RequestMapping("/api/user")
public class MemberController {
    @Autowired
    private MemberService memberService;

    /**
     * 模拟发送验证码
     */
    @PostMapping("/sendCode")
    public BaseResponse<String> sendCode(@RequestBody MemberRegisterRequest req, HttpSession session) {
        System.out.println("[sendCode] 当前sessionId: " + session.getId());
        String phoneOrEmail = req.getPhone() != null ? req.getPhone() : req.getEmail();
        if (phoneOrEmail == null || phoneOrEmail.isEmpty()) {
            return ResultUtils.error(400, "手机号或邮箱不能为空");
        }
        // 校验手机号或邮箱格式
        if (req.getPhone() != null && !req.getPhone().isEmpty()) {
            String phoneRegex = "^1[3-9]\\d{9}$";
            if (!Pattern.matches(phoneRegex, req.getPhone())) {
                return ResultUtils.error(400, "手机号格式不正确");
            }
        }
        if (req.getEmail() != null && !req.getEmail().isEmpty()) {
            String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
            if (!Pattern.matches(emailRegex, req.getEmail())) {
                return ResultUtils.error(400, "邮箱格式不正确");
            }
        }
        // 生成6位数字验证码
        String code = String.valueOf(100000 + new Random().nextInt(900000));
        // 存入session，key为 phoneOrEmail_code，值为"code:timestamp"
        long now = System.currentTimeMillis();
        session.setAttribute(phoneOrEmail + "_code", code + ":" + now);
        // 输出到后台控制台
        System.out.println("验证码发送到 " + phoneOrEmail + " ：" + code);
        // 不返回验证码给前端
        return ResultUtils.success("验证码已发送");
    }

    @PostMapping("/register")
    public BaseResponse<Member> register(@RequestBody MemberRegisterRequest req, HttpSession session) {
        System.out.println("[register] 当前sessionId: " + session.getId());
        // 1. 参数必填校验
        if (!StringUtils.hasText(req.getPassword()) ||
            (!StringUtils.hasText(req.getPhone()) && !StringUtils.hasText(req.getEmail()))) {
            return ResultUtils.error(400, "手机号/邮箱和密码不能为空");
        }
        // 2. 校验验证码
        String phoneOrEmail = req.getPhone() != null ? req.getPhone() : req.getEmail();
        String codeInSession = (String) session.getAttribute(phoneOrEmail + "_code");
        if (codeInSession == null) {
            return ResultUtils.error(401, "请先获取验证码");
        }
        String[] codeParts = codeInSession.split(":");
        String realCode = codeParts[0];
        long sendTime = codeParts.length > 1 ? Long.parseLong(codeParts[1]) : 0L;
        long now = System.currentTimeMillis();
        if (now - sendTime > 2 * 60 * 1000) { // 2分钟有效期
            session.removeAttribute(phoneOrEmail + "_code");
            return ResultUtils.error(401, "验证码已过期，请重新获取");
        }
        if (req.getCode() == null || !req.getCode().equals(realCode)) {
            return ResultUtils.error(401, "验证码错误");
        }
        // 3. 格式校验
        if (StringUtils.hasText(req.getPhone())) {
            String phoneRegex = "^1[3-9]\\d{9}$";
            if (!Pattern.matches(phoneRegex, req.getPhone())) {
                return ResultUtils.error(400, "手机号格式不正确");
            }
        }
        if (StringUtils.hasText(req.getEmail())) {
            String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
            if (!Pattern.matches(emailRegex, req.getEmail())) {
                return ResultUtils.error(400, "邮箱格式不正确");
            }
        }
        // 4. 唯一性校验
        // 5. 密码加密、保存、异常处理
        try {
            Member member = new Member();
            member.setName(req.getName() != null ? req.getName() : (req.getPhone() != null ? req.getPhone() : req.getEmail()));
            member.setPhone(req.getPhone());
            member.setEmail(req.getEmail());
            member.setPassword(req.getPassword());
            Integer mbid = memberService.register(member);
            // 返回脱敏用户信息
            member.setPassword(null);
            member.setMbid(mbid);
            return ResultUtils.success(member);
        } catch (RuntimeException e) {
            return ResultUtils.error(409, e.getMessage());
        } catch (Exception e) {
            return ResultUtils.error(500, "注册失败，请稍后重试");
        }
    }

    @PostMapping("/login")
    public BaseResponse<Member> login(@RequestBody MemberLoginRequest req) {
        String phoneOrEmail = req.getPhoneOrEmail();
        Member member = memberService.login(phoneOrEmail, req.getPassword());
        if (member == null) {
            return ResultUtils.error(401, "账号或密码错误");
        }
        member.setPassword(null);
        return ResultUtils.success(member);
    }

    @GetMapping("/ping")
    public String ping() {
        return "pong";
    }
}
